package com.banzhi.shop.fragment;

import android.annotation.SuppressLint;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.support.annotation.Nullable;

import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.banzhi.shop.R;
import com.banzhi.shop.activity.MainActivity;
import com.banzhi.shop.entity.College.CollegeCallBack;
import com.banzhi.shop.entity.College.CollegeImpl;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.LogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.view.TitleBar;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static android.content.ContentValues.TAG;

/**
 * Created by Administrator on 2018/5/8.
 */

public class CollegeFragment extends Fragment implements CollegeCallBack, View.OnClickListener {
    private CollegeImpl collegeModel;
    private List<String> CollegeData = new ArrayList<>();
    private static WebView wvCollege;
    private com.banzhi.shop.entity.College.CollegeData collegeData;
    private String msg;
    private MainActivity activity;

    private int payType = 0;
    private String record_url;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (activity == null) {
            activity = (MainActivity) context;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.college_tab1_fragment, null);
        //   Log.e("LIJIE","onCreateView");
        initView(view);
        collegeModel = new CollegeImpl();
        LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
        collegeModel.getData(this);
        return view;
    }

    private void initView(View view) {
        wvCollege = (WebView) view.findViewById(R.id.wv_college);

        WebSettings mWebSettings = wvCollege.getSettings();
        mWebSettings.setJavaScriptEnabled(true);
        TitleBar titleBar = (TitleBar) view.findViewById(R.id.tb_college);
        titleBar.setTitle("学院");
        titleBar.setRightSkip(R.mipmap.suaxin, "", this);
    }


    @Override
    public void ongetDataSuccess(Object object) {
        LogUtils.d("11111", object.toString());
        collegeData = (com.banzhi.shop.entity.College.CollegeData) object;
        msg = collegeData.getMsg();
        Log.d(TAG, "msg2222222: " + msg);
        LoadingDialogUtils.dismiss();
        showWebView();
    }

    private void showWebView() {
        wvCollege.getSettings().setJavaScriptEnabled(true);
        wvCollege.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {

                }
            }
        });

        wvCollege.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //调出微信支付
                if (url.startsWith("weixin://wap/pay?")) {
                    payType = 1;
                    record_url = "";
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                } else {
                    payType = 0;
                    record_url = url;
                }
                return false;
            }

            @SuppressLint("NewApi")
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                @SuppressLint({"NewApi", "LocalSuppress"})
                String url = null;
                url = request.getUrl().toString();
                if (url.startsWith("http://m.xlzhao.com/") && url.contains("&go_wx=1")) {
                    url = url.replaceAll("&go_wx=1", "");
                }
                //    Log.e("LIJIE","去掉弹框后的url-----"+url);
                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.d("LIJIE", "onPageFinished------" + msg);
            }


            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                // TODO Auto-generated method stub
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });

        wvCollege.loadUrl(msg);
    }

    @Override
    public void onClick(View view) {
        LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
        wvCollege.reload();
        LoadingDialogUtils.dismiss();
    }

    @Override
    public void onResume() {
        super.onResume();
        //   Log.e("LIJIE","onResume");

        if (payType == 1) {
            //重新初始化webviewF
            //     Log.e("LIJIE","支付返回刷新");

            if (TextUtils.isEmpty(record_url)) {
                //        Log.e("LIJIE","URL==null");
                wvCollege.goBack();
            } else {
                //        Log.e("LIJIE","URL==no_null");
                wvCollege.loadUrl(record_url);
            }


        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //  Log.e("LIJIE","onDestory");
        wvCollege.stopLoading();
        wvCollege.removeAllViews();
        wvCollege.destroy();
        wvCollege = null;
    }

    //浏览器回退网页而不是退出，需要在当前Activity中处理并重写该back事件；
    public static boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d(TAG, "onKeyUp keyCode:" + keyCode);
        if (wvCollege.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {

            Log.d(TAG, "keyCode:" + keyCode);
            wvCollege.goBack();   //goBack()表示返回webView的上一页面
            return true;
        }
        return false;
    }

    @Override
    public void ongetDataError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }
}
